package strutstest.actions;

import java.lang.reflect.Method;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public abstract class MultiActionByParameter extends Action {
	protected abstract String getMethodNameParameter();

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String methodName = getMethodName(request, getMethodNameParameter());
		Method m = getMethod(methodName);
		return (ActionForward) m.invoke(this, mapping, form, request, response);
	}

	private Method getMethod(String methodName) throws NoSuchMethodException {
		for(Method m : this.getClass().getDeclaredMethods()){
			m.setAccessible(true);
			if(m.getName().toUpperCase().equals(methodName.toUpperCase())){
				return m;
			}
		}
		throw new NoSuchMethodException();
	}

	private String getMethodName(HttpServletRequest request, String methodNameParameter) {
		Enumeration e = request.getParameterNames();
		while (e.hasMoreElements()) {
			String key = (String)e.nextElement();
			if(key.trim().toUpperCase().equals(key.trim().toUpperCase())){
				return request.getParameter(key);
			}
		}
		throw new RuntimeException();
	}
}





















